package com.thinkgem.jeesite.modules.erp.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.exception.CustomException;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.modules.erp.dao.WareHouseDao;
import com.thinkgem.jeesite.modules.erp.entity.Department;
import com.thinkgem.jeesite.modules.erp.entity.Goods;
import com.thinkgem.jeesite.modules.erp.entity.OutAndInWarehouseOrder;
import com.thinkgem.jeesite.modules.erp.entity.Page;
import com.thinkgem.jeesite.modules.erp.entity.Repository;
import com.thinkgem.jeesite.modules.oa.dao.OaNotifyDao;
import com.thinkgem.jeesite.modules.oa.entity.OaNotify;
import com.thinkgem.jeesite.modules.sys.entity.User;

/**
 * 入库管理
 * @author lx
 *
 */
@Service
@Transactional
public class WareHouseService extends CrudService<OaNotifyDao, OaNotify>{
	
	@Autowired
	private WareHouseDao wareHouseDao;

	//递归查询出所有部门和部门下面的员工
	public Department queryAllDepsWorkers(String depid){
		Department dep=wareHouseDao.queryDepInfo(depid);
		//根据id查询出这个部门下的员工
		List<Map<String,Object>> users = wareHouseDao.queryUsersByDep(depid);
		List<Map<String,Object>> deps = wareHouseDao.queryDepsByParent(depid);
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		
		for(Map<String,Object> map:deps){
			Department de = this.queryAllDepsWorkers((String)map.get("id"));//递归
			if(null!=de){
				Map<String,Object> one =new HashMap<String,Object>();
//				one.put("id", de.getId()+"");
				one.put("name", de.getName());
				one.put("children", de.getChildren());
				//判断是否有children，若不存在不加入列表
				if(null!=de.getChildren()&&de.getChildren().size()>0){
					list.add(one);
				}
			}
		}
		if(users.size()==0&&deps.size()==0){
			return null;
		}
		if(null!=dep){
			list.addAll(users);
			dep.setChildren(list);
			dep.setId(null);
		}
		return dep;
	}

	public List<Goods> dimQueryGoods(String keyword) {
		Map<String,Object>map=new HashMap<String,Object>();
		map.put("keyword", keyword);
		List<Goods> list = wareHouseDao.dimQueryGoods(map);
		
		return list;
	}

	public List<Goods> queryAllGoods() {
		List<Goods>list=wareHouseDao.queryAllGoods();
		return list;
	}
	
	//入库,并记录入库信息
	public void bePutInStorage(OutAndInWarehouseOrder op){
		op.setType(true);//设置为入库
		//删除订单
		wareHouseDao.deleteTemporarilyOrders(op);
		//增加入库订单基本信息
		wareHouseDao.saveInputOrderBaseInfo(op);
		List<String> list = op.getNameList();
		for(int i=0;i<list.size();i++){
			Map<String,Object>map=new HashMap<String,Object>();
			map.put("code", op.getNameList().get(i));
			map.put("amount", op.getAmountList().get(i));
			if(op.getRemarksList().size()!=0)
			map.put("remarks", op.getRemarksList().get(i));
			map.put("rep_id", op.getRepoList().get(i));//由于需求修改，rep_id不是id而是手写的仓库名字
			map.put("orderCode", op.getId());
			if(null!=op.getNameList().get(i)&&!"".equals(op.getNameList().get(i))){
				if(null!=map.get("rep_id")&&!"".equals(map.get("rep_id"))){
					//查询对应的仓库名字是否存在
//					Repository rep = wareHouseDao.queryRepositoryExist((String)map.get("rep_id"));
					//通过仓库编号查询仓库是否存在
					Repository rep = wareHouseDao.queryRepositoryExistByCode((String)map.get("rep_id"));
					//存在直接在物料表中修改其仓库编号
					
					if(null==rep){
						//不存在新建一个仓库，并修改物料表中的其仓库编号
						Repository repo=new Repository();
						repo.setRep_Name((String)map.get("rep_id"));
						wareHouseDao.saveRepositoryReturnId(repo);//新建的仓库
						map.put("rep_code", repo.getId());
					}else{
						map.put("rep_code", rep.getId());
					}
					
					wareHouseDao.updateGoodsAmountRepository(map);
				}else{
					//计算修改物品数量
					wareHouseDao.updateGoodsAmount(map);
				}
				//物品信息
				wareHouseDao.saveOrderGoodsInfo(map);
			}
			map.clear();
		}
		
	}

	public void beTakeOutStorage(OutAndInWarehouseOrder op) {
		op.setType(false);
		//删除订单
		wareHouseDao.deleteTemporarilyOrders(op);
		wareHouseDao.beTakeOutStorage(op);
		List<String> list = op.getNameList();
		for(int i=0;i<list.size();i++){
			Map<String,Object>map=new HashMap<String,Object>();
			map.put("code", op.getNameList().get(i));
			map.put("amount", op.getAmountList().get(i));
			map.put("remarks", op.getRemarksList().size()==0?null:op.getRemarksList().get(i));
			map.put("orderCode", op.getId());
			//物品信息
			wareHouseDao.saveOrderGoodsInfo(map);
			
			//由于后期删除审核模块。故直接扣除数量
			wareHouseDao.updateReduce(map);//减去出库的数量
		}
		
	}
	//查询个人的订单
	public List<OutAndInWarehouseOrder> getPersonalOrders(OutAndInWarehouseOrder order) {
		List<OutAndInWarehouseOrder>list = wareHouseDao.getPersonalOrders(order);
		return list;
	}

	public List<OutAndInWarehouseOrder> queryRelevantOrders(OutAndInWarehouseOrder order) {
		List<OutAndInWarehouseOrder>list=wareHouseDao.queryRelevantOrders(order);
		return list;
	}

	public List<Map<String, Object>> isEnough(OutAndInWarehouseOrder op) {
		List<Map<String,Object>>mapList=new ArrayList<Map<String,Object>>();
		List<String> list = op.getNameList();
		for(int i=0;i<list.size();i++){
			Integer needAmount = Integer.parseInt(op.getAmountList().get(i));//需要数量
			//根据物品编号查询库存量
			Map<String,Object>map =wareHouseDao.queryGoodsAmount(op.getNameList().get(i));
			//根据
			Integer dbAmount = Integer.parseInt((String) map.get("amount"));
			if(needAmount>dbAmount){//库存数量不够
				mapList.add(map);
			}
		}
		
		return mapList;
	}

	/**
	 * 
	 * @param code	单号
	 * @param action	执行动作	1通过3拒绝
	 * @throws CustomException 
	 */
	public void Marking(String code, String action) throws CustomException {
		
		if("1".equals(action)){
			// 查询要减少信息
			List<Map<String,Object>>list=wareHouseDao.queryReduceInfo(code);
			for(Map<String,Object> map:list){
				String needcode = (String) map.get("code");
				Integer needamount = Integer.parseInt((String) map.get("amount"));
				Map<String, Object> db = wareHouseDao.queryGoodsAmount(needcode);
				Integer dbamount = Integer.parseInt((String) db.get("amount"));
				if(dbamount<needamount){
					throw new CustomException("仓库中所需物品数量不够！");
				}
			}
			//减少库存量
			for(int i=0;i<list.size();i++){
				wareHouseDao.updateReduce(list.get(i));
			}
		}
		//修改单号状态
		Map<String,Object> ca=new HashMap<String,Object>();
		ca.put("code", code);
		ca.put("action", action);
		wareHouseDao.updateOrdersStatus(ca);
	}

	public List<Repository> queryAllRepository() {
		List<Repository>list=wareHouseDao.queryAllRepository();
		return list;
	}
	
	//删除仓库
	public void deleteRepository(String repId) {
		wareHouseDao.deleteRepository(repId);
	}

	//新增仓库
	public String addRepository(Repository repository) {
		Repository rep=wareHouseDao.queryRepositoryExist(repository.getRep_Name());
		if(null!=rep){//仓库名存在
			return rep.getRep_Name();
		}else{
			//新增
			wareHouseDao.addRepository(repository);
		}
		return null;
	}

	//修改仓库
	public String updateRepository(Repository repository) {
		Map<String,Object> map=wareHouseDao.queryRepositoryExistExcludeSelf(repository);
		if(null!=map){//仓库名存在
			return (String) map.get("rep_name");
		}else{
			//新增
			wareHouseDao.updateRepository(repository);
		}
		return null;
	}

	public List<Map<String, Object>> queryRepositoryByPage(Map<String, Object> map) {
		List<Map<String, Object>>list=wareHouseDao.queryRepositoryByPage(map);
		return list;
	}

	public String updateOrdersInfo(OutAndInWarehouseOrder op) {
		String id=wareHouseDao.queryOrdersId(op);
		op.setId(Integer.parseInt(id));
		//删除原来的的orders_goods对应的记录
		wareHouseDao.deleteOrdersInfo(id);
		//重新批量新增对应的数据
		List<String> nameList = op.getNameList();
		List<String> amountList = op.getAmountList();
		List<String> remarksList = op.getRemarksList();
		List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
		for(int i=0;i<nameList.size();i++){
			Map<String,Object>map=new HashMap<String,Object>();
			map.put("order_id", id);
			map.put("nameList", nameList.get(i));
			map.put("amountList", amountList.get(i));
			map.put("remarksList", remarksList.get(i));
			list.add(map);
		}
		wareHouseDao.foreachInsertOrdersInfo(list);
		return "1";
	}

	public Map<String, Object> ordersTimes(String type) {
		Map<String, Object>map=wareHouseDao.ordersTimes();
		//+1
		Map<String,Object>par=new HashMap<String,Object>();
		if("st".equals(type)){
			par.put("st", "st");
		}else{
			par.put("ob", "ob");
		}
		wareHouseDao.addTimesOne(par);
		return map;
	}

	public List<Repository> queryRepositoryTree(String parentid) {
		List<Repository> list = wareHouseDao.queryRepositoryTree(parentid);
		for(Repository repo : list ){
			List<Repository> children = repo.getChildren();
			for(Repository repos : children ){
				String id = repos.getId()+"";
				List<Repository> queryRepositoryTree = queryRepositoryTree(id);
				repos.setChildren(queryRepositoryTree);
			}
		}
		return list;
	}
	
	
	
	public Integer queryRepositoryMaterialAmount(Map<String, Object> map) {
		Integer amount=wareHouseDao.queryRepositoryMaterialAmount(map);
		return amount;
	}

	public String queryRepositoryName(String repository) {
		String name=wareHouseDao.queryRepositoryName(repository);
		return name;
	}

	public OutAndInWarehouseOrder queryPutInOnlyOrders(Map<String, Object> map) {
		OutAndInWarehouseOrder orders=wareHouseDao.queryPutInOnlyOrders(map);
		return orders;
	}

	public void inTemporarilySave(OutAndInWarehouseOrder op) {
		String code = op.getCode();
		//校验是否存在同样的编号的订单，若存在删除
		wareHouseDao.deleteTemporarilyOrders(op);
		wareHouseDao.inTemporarilySave(op);
		List<String> name = op.getNameList();
		for(int i=0;i<name.size();i++){
			Map<String,Object>map=new HashMap<String,Object>();
			map.put("code", op.getNameList().get(i));
			map.put("amount", op.getAmountList().get(i));
			if(op.getRemarksList().size()!=0)
			map.put("remarks", op.getRemarksList().get(i));
			if(op.getRepoList()!=null)
			map.put("rep_id", op.getRepoList().get(i));//由于需求修改，rep_id不是id而是手写的仓库名字
			map.put("orderCode", op.getId());
			wareHouseDao.saveOrderGoodsInfo(map);
			//设置物料仓库信息
			if(null!=map.get("rep_id")&&!"".equals(map.get("rep_id"))){
				wareHouseDao.updateGoodsRepository(map);
			}
			map.clear();
		}
	}
	
	public OutAndInWarehouseOrder queryPersonalUnfinishedOrders(Map<String, Object> map) {
		OutAndInWarehouseOrder orders =wareHouseDao.queryPersonalUnfinishedOrders(map);
		return orders;
	}

	public Page<OutAndInWarehouseOrder> ajQueryOrders(OutAndInWarehouseOrder order) {
		Page<OutAndInWarehouseOrder> page=new Page<OutAndInWarehouseOrder>();
		//条件下的总数量
		List<OutAndInWarehouseOrder>list=wareHouseDao.ajQueryOrders(order);
		//条件下的内容
		List<OutAndInWarehouseOrder>result=new ArrayList<OutAndInWarehouseOrder>();
		System.out.println(order.getBegin()+":"+(order.getEnd()-1));
		for(int i=order.getBegin();i<order.getEnd()-1;i++){
			
			result.add(list.get(i));
		}
		page.setRows(result);
		page.setTotal(list.size());
		return page;
	}

	


	
}
